import React, { useState, useEffect, useRef, useCallback } from 'react';
import {
  Box,
  CircularProgress,
  Typography,
  Button,
  Snackbar,
  Alert,
  Fab
} from '@mui/material';
import { Refresh, KeyboardArrowUp, KeyboardArrowDown } from '@mui/icons-material';
import { useRecommendation } from '../../hooks/useRecommendation';
import { RecommendationContent } from '../../types/recommendation/recommendation';
import { RecommendationCard } from './components';
import styles from './Recommendations.module.css';

const Recommendations: React.FC = () => {
  const [contents, setContents] = useState<RecommendationContent[]>([]);
  const [currentIndex, setCurrentIndex] = useState(0);
  const [isLoadingMore, setIsLoadingMore] = useState(false);
  const [hasReachedEnd, setHasReachedEnd] = useState(false);
  const [snackbarOpen, setSnackbarOpen] = useState(false);
  const [snackbarMessage, setSnackbarMessage] = useState('');
  const [snackbarSeverity, setSnackbarSeverity] = useState<'success' | 'error' | 'warning' | 'info'>('info');
  
  const containerRef = useRef<HTMLDivElement>(null);
  const { loading, error, fetchNextRecommendation, clearError } = useRecommendation();

  // 加载推荐内容
  const loadRecommendation = useCallback(async () => {
    if (isLoadingMore) return;
    
    setIsLoadingMore(true);
    try {
      const content = await fetchNextRecommendation();
      if (content) {
        setContents(prev => [...prev, content]);
        setHasReachedEnd(false);
      } else {
        // 没有更多内容
        if (contents.length === 0) {
          showSnackbar('暂无推荐内容，请稍后再试', 'warning');
        } else {
          setHasReachedEnd(true);
          showSnackbar('已经到底了，没有更多内容', 'info');
        }
      }
    } catch (err) {
      console.error('加载推荐内容失败:', err);
      showSnackbar('加载失败，请检查网络连接', 'error');
    } finally {
      setIsLoadingMore(false);
    }
  }, [fetchNextRecommendation, isLoadingMore, contents.length]);

  // 显示提示消息
  const showSnackbar = (message: string, severity: 'success' | 'error' | 'warning' | 'info') => {
    setSnackbarMessage(message);
    setSnackbarSeverity(severity);
    setSnackbarOpen(true);
  };

  // 处理滚动事件
  const handleScroll = useCallback(() => {
    if (!containerRef.current || isLoadingMore || hasReachedEnd) return;

    const container = containerRef.current;
    const scrollTop = container.scrollTop;
    const scrollHeight = container.scrollHeight;
    const clientHeight = container.clientHeight;
    
    // 计算当前显示的内容索引
    const newIndex = Math.round(scrollTop / clientHeight);
    if (newIndex !== currentIndex && newIndex < contents.length) {
      setCurrentIndex(newIndex);
    }

    // 检查是否需要加载更多内容
    const threshold = clientHeight * 0.8; // 提前80%的距离开始加载
    if (scrollTop + clientHeight >= scrollHeight - threshold) {
      loadRecommendation();
    }
  }, [currentIndex, contents.length, isLoadingMore, hasReachedEnd, loadRecommendation]);

  // 初始化加载
  useEffect(() => {
    if (contents.length === 0) {
      loadRecommendation();
    }
  }, []);

  // 绑定滚动事件
  useEffect(() => {
    const container = containerRef.current;
    if (container) {
      container.addEventListener('scroll', handleScroll, { passive: true });
      return () => container.removeEventListener('scroll', handleScroll);
    }
  }, [handleScroll]);

  // 处理错误重试
  const handleRetry = () => {
    clearError();
    setContents([]);
    setCurrentIndex(0);
    setHasReachedEnd(false);
    loadRecommendation();
  };

  // 处理内容错误
  const handleContentError = (errorMessage: string) => {
    showSnackbar(errorMessage, 'error');
  };

  // 向上滑动
  const scrollUp = useCallback(() => {
    if (currentIndex > 0) {
      const newIndex = currentIndex - 1;
      setCurrentIndex(newIndex);
      if (containerRef.current) {
        containerRef.current.scrollTo({
          top: newIndex * containerRef.current.clientHeight,
          behavior: 'smooth'
        });
      }
    }
  }, [currentIndex]);

  // 向下滑动
  const scrollDown = useCallback(() => {
    if (currentIndex < contents.length - 1) {
      const newIndex = currentIndex + 1;
      setCurrentIndex(newIndex);
      if (containerRef.current) {
        containerRef.current.scrollTo({
          top: newIndex * containerRef.current.clientHeight,
          behavior: 'smooth'
        });
      }
    } else if (!isLoadingMore && !hasReachedEnd) {
      // 如果是最后一个内容且还能加载更多，则加载新内容
      loadRecommendation();
    }
  }, [currentIndex, contents.length, isLoadingMore, hasReachedEnd, loadRecommendation]);

  // 键盘事件处理
  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === 'ArrowUp') {
        event.preventDefault();
        scrollUp();
      } else if (event.key === 'ArrowDown') {
        event.preventDefault();
        scrollDown();
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [scrollUp, scrollDown]);

  // 如果初始加载失败
  if (error && contents.length === 0) {
    return (
      <div className={styles.container}>
        <div className={styles.errorWrapper}>
          <Typography variant="h6" className={styles.errorMessage}>
            {error}
          </Typography>
          <Button
            variant="contained"
            startIcon={<Refresh />}
            onClick={handleRetry}
            className={styles.retryButton}
          >
            重试
          </Button>
        </div>
      </div>
    );
  }

  return (
    <div className={styles.container}>
      {/* 初始加载状态 */}
      {loading && contents.length === 0 && (
        <div className={styles.loadingWrapper}>
          <CircularProgress size={60} />
          <Typography variant="body1" sx={{ mt: 2, color: 'white' }}>
            正在为您推荐精彩内容...
          </Typography>
        </div>
      )}

      {/* 内容列表 */}
      <div 
        ref={containerRef}
        className={styles.contentWrapper}
      >
        {contents.map((content, index) => (
          <div key={`${content.id}-${index}`} className={styles.contentItem}>
            <RecommendationCard
              content={content}
              isActive={index === currentIndex}
              onError={handleContentError}
            />
          </div>
        ))}

        {/* 加载更多指示器 */}
        {isLoadingMore && contents.length > 0 && (
          <div className={styles.contentItem}>
            <Box
              display="flex"
              flexDirection="column"
              alignItems="center"
              justifyContent="center"
              height="100%"
              color="white"
            >
              <CircularProgress size={40} color="primary" />
              <Typography variant="body2" sx={{ mt: 2 }}>
                正在加载更多内容...
              </Typography>
            </Box>
          </div>
        )}
      </div>

      {/* 上下滑动按钮 */}
      {contents.length > 0 && (
        <div className={styles.navigationButtons}>
          {/* 向上按钮 */}
          <Fab
            size="medium"
            onClick={scrollUp}
            disabled={currentIndex === 0}
            className={styles.navButton}
          >
            <KeyboardArrowUp />
          </Fab>

          {/* 向下按钮 */}
          <Fab
            size="medium"
            onClick={scrollDown}
            disabled={currentIndex === contents.length - 1 && hasReachedEnd}
            className={styles.navButton}
          >
            <KeyboardArrowDown />
          </Fab>
        </div>
      )}

      {/* 到底提示 */}
      {hasReachedEnd && contents.length > 0 && (
        <div className={styles.endMessage}>
          <Typography variant="body2">
            已经到底了，没有更多内容
          </Typography>
        </div>
      )}

      {/* 提示消息 */}
      <Snackbar
        open={snackbarOpen}
        autoHideDuration={3000}
        onClose={() => setSnackbarOpen(false)}
        anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
      >
        <Alert
          severity={snackbarSeverity}
          onClose={() => setSnackbarOpen(false)}
          sx={{ width: '100%' }}
        >
          {snackbarMessage}
        </Alert>
      </Snackbar>
    </div>
  );
};

export default Recommendations; 